package threading;

import java.util.concurrent.PriorityBlockingQueue;

class MyTask implements Comparable<MyTask>{
    public Runnable runnable;
    public long time;

    public void MyTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }


    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer{
    PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    Object locker = new Object();

    //  实现一个方法，将对象放进队列
    public void schedule(Runnable runnable,long delay){
        MyTask myTask = new MyTask();
        queue.put(myTask);
        synchronized (locker) {
            locker.notify();
        }
    }

    public MyTimer(){
        Thread thread = new Thread( () -> {
            while (true){
                try {
                    synchronized (locker) {
                        MyTask myTask = queue.take();
                        long currentTime = System.currentTimeMillis();
                        if(currentTime >= myTask.time){
                            myTask.runnable.run();
                        }else{
                            queue.put(myTask);
                            locker.wait();
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        } );
        thread.start();
    }
}

public class ThreadDemo13 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        }, 4000);


        System.out.println("hello 0");
    }
}
